<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>Dubbo SPI 机制 | flyingzc's blog</title><meta name="author" content="flyingzc"><meta name="copyright" content="flyingzc"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="SPI 机制SPI 作用SPI 全称为 Service Provider Interface, 是一种服务发现机制. SPI 的本质是将接口实现类的全限定名配置在文件中, 并由服务加载器读取配置文件, 加载实现类. 这样可以在运行时, 动态为接口替换实现类. 正因此特性, 我们可以很容易的通过 SPI 机制为我们的程序提供拓展功能. Dubbo 里面有很多个组件, 每个组件在框架中都是以接口的形式">
<meta property="og:type" content="article">
<meta property="og:title" content="Dubbo SPI 机制">
<meta property="og:url" content="https://flyingzc.github.io/articles/dubbo/dubbo02-spi.html">
<meta property="og:site_name" content="flyingzc&#39;s blog">
<meta property="og:description" content="SPI 机制SPI 作用SPI 全称为 Service Provider Interface, 是一种服务发现机制. SPI 的本质是将接口实现类的全限定名配置在文件中, 并由服务加载器读取配置文件, 加载实现类. 这样可以在运行时, 动态为接口替换实现类. 正因此特性, 我们可以很容易的通过 SPI 机制为我们的程序提供拓展功能. Dubbo 里面有很多个组件, 每个组件在框架中都是以接口的形式">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://flyingzc.github.io/images/zc-icon.jpeg">
<meta property="article:published_time" content="2019-11-26T16:00:00.000Z">
<meta property="article:modified_time" content="2025-01-21T01:51:41.210Z">
<meta property="article:author" content="flyingzc">
<meta property="article:tag" content="Dubbo">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://flyingzc.github.io/images/zc-icon.jpeg"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "Dubbo SPI 机制",
  "url": "https://flyingzc.github.io/articles/dubbo/dubbo02-spi.html",
  "image": "https://flyingzc.github.io/images/zc-icon.jpeg",
  "datePublished": "2019-11-26T16:00:00.000Z",
  "dateModified": "2025-01-21T01:51:41.210Z",
  "author": [
    {
      "@type": "Person",
      "name": "flyingzc",
      "url": "https://flyingzc.github.io/"
    }
  ]
}</script><link rel="shortcut icon" href="/images/zc-icon.jpeg"><link rel="canonical" href="https://flyingzc.github.io/articles/dubbo/dubbo02-spi.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google-site-verification" content="DentpX3LnP_WNgEeFnNIcTZZky-Bby-zL-uI_9GqTAw"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!false && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script async="async" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(adsbygoogle = window.adsbygoogle || []).push({
  google_ad_client: '',
  enable_page_level_ads: 'true'
});</script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'null',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Dubbo SPI 机制',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/self/github-dark.css"><meta name="generator" content="Hexo 7.0.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">flyingzc's blog</span></a><a class="nav-page-title" href="/"><span class="site-name">Dubbo SPI 机制</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">Dubbo SPI 机制</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2019-11-26T16:00:00.000Z" title="发表于 2019-11-27 00:00:00">2019-11-27</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-01-21T01:51:41.210Z" title="更新于 2025-01-21 09:51:41">2025-01-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Dubbo/">Dubbo</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><h1 id="SPI-机制"><a href="#SPI-机制" class="headerlink" title="SPI 机制"></a>SPI 机制</h1><h2 id="SPI-作用"><a href="#SPI-作用" class="headerlink" title="SPI 作用"></a>SPI 作用</h2><p>SPI 全称为 Service Provider Interface, 是一种服务发现机制.</p>
<p>SPI 的本质是将接口实现类的全限定名配置在文件中, 并由服务加载器读取配置文件, 加载实现类.</p>
<p>这样可以在运行时, 动态为接口替换实现类. 正因此特性, 我们可以很容易的通过 SPI 机制为我们的程序提供拓展功能.</p>
<p>Dubbo 里面有很多个组件, 每个组件在框架中都是以接口的形式抽象出来. 具体的实现又分很多种, 在程序执行时根据用户的配置来按需取接口的实现类.</p>
<h2 id="Dubbo-实现的-SPI-与-JDK-自带的-SPI-的区别"><a href="#Dubbo-实现的-SPI-与-JDK-自带的-SPI-的区别" class="headerlink" title="Dubbo 实现的 SPI 与 JDK 自带的 SPI 的区别"></a>Dubbo 实现的 SPI 与 JDK 自带的 SPI 的区别</h2><p>摘自官网</p>
<ul>
<li><p>JDK 标准的 SPI 会一次性实例化扩展点所有实现, 如果有扩展实现初始化很耗时, 但如果没用上也加载, 会很浪费资源.</p>
</li>
<li><p>如果扩展点加载失败, 连扩展点的名称都拿不到了.<br>比如: JDK 标准的 ScriptEngine, 通过 getName() 获取脚本类型的名称, 但如果 RubyScriptEngine 因为所依赖的 jruby.jar 不存在, 导致 RubyScriptEngine 类加载失败, 这个失败原因被吃掉了, 和 ruby 对应不起来, 当用户执行 ruby 脚本时, 会报不支持 ruby, 而不是真正失败的原因.</p>
</li>
<li><p>增加了对扩展点 IoC 和 AOP 的支持, 一个扩展点可以直接 setter 注入其它扩展点.</p>
</li>
<li><p>JDK 的 SPI 要用 for 循环, 然后 if 判断才能获取到指定的 SPI 对象, Dubbo 用指定的 key 就可以获取.</p>
</li>
<li><p>JDK 的 SPI 不支持默认值, Dubbo 增加了默认值的设计.</p>
</li>
</ul>
<h2 id="SPI-配置和使用"><a href="#SPI-配置和使用" class="headerlink" title="SPI 配置和使用"></a>SPI 配置和使用</h2><p>只有在接口打了 @SPI 注解的接口类才会去查找扩展点实现.</p>
<p>会依次从这几个文件中读取扩展点</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">META-INF/Dubbo/internal/   // Dubbo 内部实现的各种扩展都放在了这个目录了<br>META-INF/Dubbo/<br>META-INF/services/<br></code></pre></td></tr></table></figure>

<p>比如</p>
<ol>
<li><p>Protocol 接口, 接口上打了 @SPI 注解, 默认拓展点名字为 Dubbo</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@SPI(&quot;Dubbo&quot;)</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">Protocol</span>&#123;<br><br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>查找 Dubbo-rpc-default 模块下 META-INF&#x2F;Dubbo&#x2F;internal&#x2F;com.alibaba.Dubbo.rpc.Protocol 中的配置</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">Dubbo=com.alibaba.Dubbo.rpc.protocol.Dubbo.DubboProtocol<br></code></pre></td></tr></table></figure>
</li>
<li><p>会用 ExtensionLoader 类加载实现<br>Dubbo&#x3D;com.alibaba.Dubbo.rpc.protocol.Dubbo.DubboProtocol</p>
</li>
<li><p>获取拓展类对象的代码示例</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 通过 ExtensionLoader.getExtensionLoader() 方法获取一个 ExtensionLoader 实例</span><br>ExtensionLoader&lt;Protocol&gt; extensionLoader = ExtensionLoader.getExtensionLoader(Protocol.class);<br><br><span class="hljs-comment">// 然后再通过 ExtensionLoader.getExtension() 方法获取拓展类对象</span><br><span class="hljs-type">Protocol</span> <span class="hljs-variable">dubboProtocol</span> <span class="hljs-operator">=</span> extensionLoader.getExtension(<span class="hljs-string">&quot;Dubbo&quot;</span>);<br></code></pre></td></tr></table></figure></li>
</ol>
<h2 id="Dubbo-拓展点加载机制相关注解和组件"><a href="#Dubbo-拓展点加载机制相关注解和组件" class="headerlink" title="Dubbo 拓展点加载机制相关注解和组件"></a>Dubbo 拓展点加载机制相关注解和组件</h2><p>@SPI</p>
<p>@Adaptive</p>
<p>@Activate</p>
<h3 id="SPI-注解"><a href="#SPI-注解" class="headerlink" title="@SPI 注解"></a>@SPI 注解</h3><p>@SPI 注解作用于扩展点的接口上,<code>表明该接口是一个扩展点</code>. 可以被 Dubbo 的 ExtentionLoader 加载, 如果没有此 ExtensionLoader 调用会异常.</p>
<h3 id="Adaptive-注解"><a href="#Adaptive-注解" class="headerlink" title="@Adaptive 注解"></a>@Adaptive 注解</h3><ol>
<li><p>在类上加 @Adaptive 注解的类, 会创建对应类型的 Adaptive 类 缓存起来. 代码里搜了一下, 有 AdaptiveExtensionFactory, AdaptiveCompiler 这两个类上打了 @Adaptive 注解.</p>
</li>
<li><p>在方法上加 @Adaptive 注解, 会先动态生成适配类的 Java 代码 (可以打断点在 ExtensionLoader.createAdaptiveExtensionClassCode() 中看到生成的类), 再默认用 Javassist 生成动态编译的 Adaptive 字节码.</p>
</li>
</ol>
<p>ExtensionLoader.loadFile() 时: 会判断类名是否含有 @Adaptive 注解. 若有, 则将此类作为适配类 缓存起来. (如果一个接口的所有实现类都没有类上打上这个注解的情况, 则会用 Javassist 生成一个 Adaptive 类)</p>
<h3 id="Activate-注解"><a href="#Activate-注解" class="headerlink" title="@Activate 注解"></a>@Activate 注解</h3><p>可以被框架中自动激活加载扩展, 这个注解用于配置扩展被自动激活的加载条件.</p>
<p>用户通过 group 和 value 配置激活条件. 被 @Activate 注解的扩展点在满足某种条件时会被激活, 它一般用来配合 filter, 声明他们的使用场景.</p>
<h3 id="Wrapper"><a href="#Wrapper" class="headerlink" title="Wrapper"></a>Wrapper</h3><p>Wrapper 类同样实现了扩展点接口, 但是 Wrapper 不是扩展点的真正实现. 它的用途主要是用于从 ExtensionLoader 返回扩展点时, 包装在真正的扩展点实现外层. 即从 ExtensionLoader 中返回的实际上是 Wrapper 类的实例, Wrapper 持有了实际的扩展点实现类.</p>
<p>扩展点的 Wrapper 类可以有多个, 也可以根据需要新增.</p>
<p>通过 Wrapper 类可以把所有扩展点公共逻辑移至 Wrapper 中. 新加的 Wrapper 在所有的扩展点上添加了逻辑, 有些类似 AOP, 即 Wrapper 代理了扩展点.</p>
<h3 id="ExtensionLoader"><a href="#ExtensionLoader" class="headerlink" title="ExtensionLoader"></a>ExtensionLoader</h3><p>ExtensionLoader 是扩展点载入器, 用于载入 Dubbo 中的各种可配置组件, 比如: 动态代理方式 (ProxyFactory), 负载均衡策略(LoadBalance),RCP 协议(Protocol), 拦截器(Filter), 容器类型(Container), 集群方式(Cluster) 和注册中心类型 (RegistryFactory) 等.</p>
<h1 id="获取-ExtensionLoader-流程"><a href="#获取-ExtensionLoader-流程" class="headerlink" title="获取 ExtensionLoader 流程"></a>获取 ExtensionLoader 流程</h1><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">- ExtensionLoader&lt;Protocol&gt; loader = ExtensionLoader.getExtensionLoader(Protocol.class)<br>    根据拓展点的接口, 获得拓展加载器. 如根据 Protocol 接口获取它对应的 ExtensionLoader<br>    - ExtensionLoader.getExtensionLoader(Class&lt;T&gt; type) 中<br>    - 1.type 必须是接口<br>    - 2.type 上包含 @SPI 注解<br>    - 3. 根据 type 尝试从 EXTENSION_LOADERS 缓存中获取 ExtensionLoader<br>    - 4. 在 3 中获取不到, 则 new ExtensionLoader&lt;T&gt;(type) 创建并缓存起来<br>        - ExtensionLoader(Class&lt;?&gt; type) 构造器中, 若传入的 type 不是 ExtensionFactory 类型, 则会获取 ExtensionFactory 的 adaptiveExtension 赋值到当前 ExtensionLoader 对象的 objectFactory 属性中, 这个 objectFactory 类似于 IoC 容器, 用于向拓展对象注入依赖的属性.<br>            - // 参见 objectFactory 创建的逻辑<br>    - 5. 返回 ExtensionLoader<br></code></pre></td></tr></table></figure>

<h1 id="获取-AdaptiveExtension-流程"><a href="#获取-AdaptiveExtension-流程" class="headerlink" title="获取 AdaptiveExtension 流程"></a>获取 AdaptiveExtension 流程</h1><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">- Protocol adaptiveExtension = loader.getAdaptiveExtension()<br>    注解在接口的方法上, SPI 机制可以根据接口动态地生成自适应类 xxx$Adaptive, 并实例化这个类并返回<br>    - ExtensionLoader.getAdaptiveExtension() 中<br>    - 1. 先尝试从 cachedAdaptiveInstance 缓存中获取 adaptive 对象<br>    - 2. 在 1 中获取不到, 则 createAdaptiveExtension() 创建 adaptive 对象并缓存起来<br>        - ExtensionLoader.createAdaptiveExtension() 中<br>        - 1.(T) getAdaptiveExtensionClass().newInstance()<br>            获取 adaptive 拓展类<br>            - ExtensionLoader.getAdaptiveExtensionClass() 中<br>            - 1.getExtensionClasses()<br>                获取所有拓展实现类<br>                - ExtensionLoader.getExtensionClasses() 中<br>                - 1. 尝试从 cachedClasses 中获取拓展实现类数组<br>                - 2. 获取不到则 classes = loadExtensionClasses() 从配置文件中加载拓展实现类列表并缓存<br>                    - ExtensionLoader.loadExtensionClasses() 中<br>                    - 1. 从接口, 如 Protocol 接口上获取 @SPI 注解的 value 属性值, 如 `@SPI(&quot;dubbo&quot;),value` 就是 dubbo, 作为默认拓展名<br>                    - 2. 分别从 META-INF/dubbo/internal/,META-INF/dubbo/,META-INF/services / 路径下读取配置文件, 加载拓展实现类列表<br>                        - ExtensionLoader.loadFile() 中<br>                        - 1. 根据文件名用类加载器获取 urls 数组<br>                        - 2. 遍历 urls 数组, 用流一行行读取配置文件<br>                        - 3.1. 根据配置的类名创建 Class 对象<br>                        - 3.2. 判断 class 上是否含有 @Adaptive 注解. 若有, 缓存到 cachedAdaptiveClass 中<br>                        - 3.3. 若实现类中没有 @Adaptive 注解<br>                        - 3.3.1. 判断实现类是否存在入参为接口的构造器 (比如 ProtocolFilterWrapper 类是否还有入参为 Protocol 接口的构造器, public ProtocolFilterWrapper(Protocol protocol), 若有的话说明它是 Wrapper 类), 添加到 wrappers 中<br>                        - 3.3.2. 既不是适配对象 (@Adaptive), 也不是 wrapped 的对象, 那就是扩展点的具体实现对象, 可以有多个. 缓存到 cachedNames 和 extensionClasses 中, 分别为 class -&gt; name 的映射 和 name -&gt; class 的映射<br>            - 2. 在 1 中, 若配置的类上有 @Adaptive 注解, 则缓存到 cachedAdaptiveClass 中. 此处取到直接返回 cachedAdaptiveClass. 若没有 adaptive 类, 则走下面生成 adaptive 类<br>            - 3.createAdaptiveExtensionClass()<br>                自动生成自适应拓展的代码实现, 并编译后返回该类<br>                - ExtensionLoader.createAdaptiveExtensionClass() 中<br>                - 1.createAdaptiveExtensionClassCode()<br>                    生成 Adaptive 类的代码 code<br>                - 2. 利用 dubbo 的 SPI 扩展机制获取 Compiler 的适配类, 此处为 AdaptiveCompiler 对象<br>                - 3.compiler.compile(code, classLoader) 编译上面生成的 adaptive 代码<br>                    - AdaptiveCompiler.compile() 中<br>                    - 1.compiler = loader.getDefaultExtension() 获得默认的 Compiler 拓展对象<br>                    - 2.compiler.compile(code, classLoader) 编译类<br>                        - AbstractCompiler.compile()<br>                            - JavassistCompiler.doCompile()<br>                - 4. 返回编译后的 class<br>        - 2.injectExtension()<br>            注入依赖<br>            - // 参见 SPI IOC 流程<br>        - 3. 创建 Wrapper 拓展对象<br>            - // 参见 SPI AOP 流程<br>    - 3. 返回 adaptive 对象<br></code></pre></td></tr></table></figure>

<h1 id="根据-name-获取拓展点对象的流程"><a href="#根据-name-获取拓展点对象的流程" class="headerlink" title="根据 name 获取拓展点对象的流程"></a>根据 name 获取拓展点对象的流程</h1><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">- Protocol dubboProtocol = loader.getExtension(&quot;dubbo&quot;);<br>      返回指定名字的扩展对象<br>    - ExtensionLoader.getExtension(name) 中<br>    - 1. 从 cachedInstances 获取对应的拓展对象<br>    - 2. 若获取不到, 创建 Holder 对象, 并缓存<br>    - 3. 通过 instance = createExtension(name) 填充 holder.value 属性<br>        - 1. 之前的从配置文件中加载拓展类的逻辑<br>        - 2. 缓存到 EXTENSION_INSTANCES 中<br>        - 3. 注入依赖的属性 injectExtension(instance)<br>            - ExtensionLoader.injectExtension() 中<br>            - 1. 遍历 class 中的所有方法找到 setter 方法<br>            - 2. 对于每一个 setter 方法 // 参见 SPI IOC 流程<br></code></pre></td></tr></table></figure>

<h1 id="objectFactory-创建的逻辑"><a href="#objectFactory-创建的逻辑" class="headerlink" title="objectFactory 创建的逻辑"></a>objectFactory 创建的逻辑</h1><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">- objectFactory(即 AdaptiveExtensionFactory) 创建的逻辑<br>    - 在 ExtensionLoader 的构造方法中会判断当前传入的对象类型<br>    - 1. 如果 type 是 ExtensionFactory 类型, 则 objectFactory 设为 null<br>    - 2.type 不是 ExtensionFactory 类型, 则会创建 ExtensionFactory objectFactory 用于后面给 拓展对象 注入依赖的属性<br>        - 1. 从配置文件中获取 adaptive 类的逻辑<br>        - 2.AdaptiveExtensionFactory 构造器中<br>        - 获取 ExtensionFactory 的 ExtensionLoader, 用 loader 获取支持的 extensions, 此处为 SPIExtensionFactory 和 SpringExtensionFactory<br></code></pre></td></tr></table></figure>

<h1 id="SPI-IOC-流程"><a href="#SPI-IOC-流程" class="headerlink" title="SPI IOC 流程"></a>SPI IOC 流程</h1><p>ExtensionLoader.injectExtension() 这个方法中, 会通过 IOC 机制注入拓展点对象的依赖.<br><img src="https://gitee.com/flyingzc/MyImg/raw/master/img/dubbo/2019-11-28-11-03-56.png" alt="ExtensionLoader.injectExtension() 被调用的地方"><br>查看调用发现, 在创建拓展对象 和 创建自适应拓展对象 时, 都会调用该方法完成依赖注入.</p>
<p>原理就是:<br>遍历当前对象的所有方法, 找出 setter 方法, 获取参数名和参数类型. 通过 ExtensionFactory 去完成依赖注入.<br>ExtensionFactory 在之前 ExtensionLoader 创建时使用的是 AdaptiveExtensionFactory 的实现.<br>AdaptiveExtensionFactory 会调用 SPIExtensionFactory 去获取依赖的拓展对象.<br>SPIExtensionFactory 给当前拓展点对象注入的均是 adaptiveExtension, 这样在运行期可以动态切换依赖的具体实现.</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">- AdaptiveExtensionFactory 注入依赖的流程<br>    - 当有实例调用 injectExtension(instance) 要注入依赖时, 会遍历这个对象里的所有方法, 找出 setter 方法, 如 setXxx(X xxx) 则传入参数类型 和 参数名<br>    - AdaptiveExtensionFactory.getExtension(type, name) 中<br>        - 1. 遍历 SPIExtensionFactory 和 SpringExtensionFactory<br>        - 2.factory.getExtension(type, name) 获取该属性的 extension<br>            - SPIExtensionFactory.getExtension(type, name) 中<br>            - 1. 类型必须是接口且有 @SPI 注解, 才会通过 ExtensionLoader 加载 adaptiveExtension 拓展, 否则返回 null<br>    - 如果有 adaptiveExtension 拓展, 则反射调用 setter 方法注入<br></code></pre></td></tr></table></figure>

<p>SpiExtensionFactory.getExtension(type, name) 代码如下:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> &lt;T&gt; T <span class="hljs-title function_">getExtension</span><span class="hljs-params">(Class&lt;T&gt; type, String name)</span> &#123;<br>    <span class="hljs-keyword">if</span> (type.isInterface() &amp;&amp; type.isAnnotationPresent(SPI.class)) &#123; <span class="hljs-comment">// 接口类型 且 有 @SPI 注解</span><br>        <span class="hljs-comment">// 加载拓展接口对应的 ExtensionLoader 对象</span><br>        ExtensionLoader&lt;T&gt; loader = ExtensionLoader.getExtensionLoader(type);<br>        <span class="hljs-comment">// 加载拓展对象</span><br>        <span class="hljs-keyword">if</span> (!loader.getSupportedExtensions().isEmpty()) &#123;<br>            <span class="hljs-keyword">return</span> loader.getAdaptiveExtension();<br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="SPI-AOP-流程"><a href="#SPI-AOP-流程" class="headerlink" title="SPI AOP 流程"></a>SPI AOP 流程</h1><p>在 ExtensionLoader.createExtension(name) 方法中, 根据 name 获取到拓展点实现类 并 通过 injectExtension() 完成依赖注入后, 会创建 Wrapper 对象.<br>就是获取当前对象的所有 wrapper(这些 wapper 是在读取配置文件时判断有参数为对应的接口类型的构造器 来添加的), 然后调用有参构造器一层一层的通过 injectExtension() 包装起来.</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">- SPI AOP 流程<br>    - 1. 遍历从配置文件中加载的 wrapperClasses<br>    - 2.1. 使用带参的构造器创建 Wrapper 对象<br>    - 2.2. 使用 wrapper 对象调用 injectExtension() 返回 instance<br>    - 2.3. 每遍历一次, 就将 wapper 对象嵌套了一层<br></code></pre></td></tr></table></figure>

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">- SPI @Activate 缓存到 cachedActivates 流程<br>    - ExtensionLoader.loadFile() 里判断类上有 Activate 注解, 则添加到缓存中.<br></code></pre></td></tr></table></figure>

<p>ExtensionLoader.createExtension(name) 代码如下:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">private</span> T <span class="hljs-title function_">createExtension</span><span class="hljs-params">(String name)</span> &#123;<br>    <span class="hljs-comment">// 1. 获得拓展名对应的拓展实现类</span><br>    Class&lt;?&gt; clazz = getExtensionClasses().get(name);<br>    <span class="hljs-comment">// ...</span><br><br>    <span class="hljs-comment">// 2. 注入依赖的属性</span><br>    injectExtension(instance);<br><br>    <span class="hljs-comment">// 3. 创建 Wrapper 拓展对象</span><br>    Set&lt;Class&lt;?&gt;&gt; wrapperClasses = cachedWrapperClasses;<br>    <span class="hljs-keyword">if</span> (wrapperClasses != <span class="hljs-literal">null</span> &amp;&amp; !wrapperClasses.isEmpty()) &#123;<span class="hljs-comment">// 先实例化扩展点的实现, 再判断此时是否有此扩展点的包装类缓存, 有的话利用 wrapper 增强这个扩展点实现的功能</span><br>        <span class="hljs-keyword">for</span> (Class&lt;?&gt; wrapperClass : wrapperClasses) &#123;<br>            <span class="hljs-comment">// 包装</span><br>            instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance)); <span class="hljs-comment">// 包装后又赋值给 instance, 所以最终 Wrapper 是一层层嵌套的</span><br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> instance;<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="SPI-Activate-流程"><a href="#SPI-Activate-流程" class="headerlink" title="SPI @Activate 流程"></a>SPI @Activate 流程</h1><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">- SPI @Activate 流程<br>    - ExtensionLoader.getActivateExtension(url, values, group)<br>    - 1. 通过 getExtensionClasses() 获得拓展实现类列表<br>    - 2. 遍历 cachedActivates<br>    - 2.1.isMatchGroup() 判断 activate 对象的 group 配置是否和传入的 group 匹配<br>    - 2.2. 若上一步匹配, 则通过 getExtension(name) 获得拓展对象<br>    - 2.3. 判断传入的 names 是否匹配, isActive(activate, url) 通过 activate.value 值判断是否激活<br>    - 2.4. 若上面条件都满足, 添加到 list 里, 并通过 ActivateComparator 给 activate 列表排序<br>        - ActivateComparator.compare() 排序逻辑<br>        - 1. 获取比较的两个类上的 Activate 注解, 通过 before 或 after 属性进行排序<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">* Get activate extensions.</span><br><span class="hljs-comment">*</span><br><span class="hljs-comment">* 获得符合自动激活条件的拓展对象数组</span><br><span class="hljs-comment">*/</span><br><span class="hljs-keyword">public</span> List&lt;T&gt; <span class="hljs-title function_">getActivateExtension</span><span class="hljs-params">(URL url, String[] values, String group)</span> &#123;<br>    List&lt;T&gt; exts = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span>&lt;T&gt;();<br>    List&lt;String&gt; names = values == <span class="hljs-literal">null</span> ? <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span>&lt;String&gt;(<span class="hljs-number">0</span>) : Arrays.asList(values);<br>    <span class="hljs-keyword">if</span> (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) &#123;<br>        <span class="hljs-comment">// 获得拓展实现类列表</span><br>        getExtensionClasses();<br>        <span class="hljs-keyword">for</span> (Map.Entry&lt;String, Activate&gt; entry : cachedActivates.entrySet()) &#123; <span class="hljs-comment">// 遍历 cachedActivates</span><br>            <span class="hljs-type">String</span> <span class="hljs-variable">name</span> <span class="hljs-operator">=</span> entry.getKey();<br>            <span class="hljs-type">Activate</span> <span class="hljs-variable">activate</span> <span class="hljs-operator">=</span> entry.getValue();<br>            <span class="hljs-keyword">if</span> (isMatchGroup(group, activate.group())) &#123; <span class="hljs-comment">// 匹配分组</span><br>                <span class="hljs-comment">// 获得拓展对象</span><br>                <span class="hljs-type">T</span> <span class="hljs-variable">ext</span> <span class="hljs-operator">=</span> getExtension(name);<br>                <span class="hljs-keyword">if</span> (!names.contains(name)<br>                        &amp;&amp; !names.contains(Constants.REMOVE_VALUE_PREFIX + name)<br>                        &amp;&amp; isActive(activate, url)) &#123; <span class="hljs-comment">// 判断是否激活</span><br>                    exts.add(ext);<br>                &#125;<br>            &#125;<br>        &#125;<br>        <span class="hljs-comment">// 排序</span><br>        Collections.sort(exts, ActivateComparator.COMPARATOR);<br>    &#125;<br>    <span class="hljs-comment">// ...</span><br>    <span class="hljs-keyword">return</span> exts;<br>&#125;<br></code></pre></td></tr></table></figure>
<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10/dist/style.css"><script src="https://fastly.jsdelivr.net/npm/d3@7"></script><script src="https://fastly.jsdelivr.net/npm/markmap-view@0.18.10"></script><script src="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10"></script>
<link rel="stylesheet" href="/css/markmap.css">

<script src="/js/markmap.js"></script>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io">flyingzc</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io/articles/dubbo/dubbo02-spi.html">https://flyingzc.github.io/articles/dubbo/dubbo02-spi.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="https://flyingzc.github.io" target="_blank">flyingzc's blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Dubbo/">Dubbo</a></div><div class="post-share"><div class="social-share" data-image="/images/zc-icon.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related" href="/articles/dubbo/dubbo01-overview.html" title="Dubbo 整理"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-11-26</div><div class="info-item-2">Dubbo 整理</div></div><div class="info-2"><div class="info-item-1">整理自官网, 对整体理解 Dubbo 很有作用. 作用Apache Dubbo 是一款高性能, 轻量级的 Java RPC 框架. 三大核心能力面向接口的远程方法调用 智能容错和负载均衡 以及服务自动注册和发现 健壮性监控中心宕掉不影响使用, 只是丢失部分采样数据. 数据库宕掉后, 注册中心仍能通过缓存提供服务列表查询, 但不能注册新服务. 注册中心对等集群, 任意一台宕掉后, 将自动切换到另一台. 注册中心全部宕掉后, 服务提供者 和 服务消费者 仍能通过本地缓存通讯. 服务提供者无状态, 任意一台宕掉后, 不影响使用. 服务提供者全部宕掉后, 服务消费者应用将无法使用, 并 无限次重连等待服务提供者恢复. 伸缩性注册中心为对等集群, 可动态增加机器部署实例, 所有客户端将自动发现新的注册中心. 服务提供者无状态, 可动态增加机器部署实例, 注册中心将推送新的服务提供者信息给消费者. 协议 Dubbo 协议采用 NIO 复用单一长连接, 并使用线程池并发处理请求, 减少握手和加大并发效率, 性能较好(推荐使用)在大文件传输时, 单一连接会成为瓶颈可用于生产环境  Rmi...</div></div></div></a><a class="pagination-related" href="/articles/dubbo/dubbo04-refer.html" title="Dubbo 服务引用"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-11-29</div><div class="info-item-2">Dubbo 服务引用</div></div><div class="info-2"><div class="info-item-1">官网 客户端服务引用客户端服务引用 demo12DemoService demoService = (DemoService) context.getBean(&quot;demoService&quot;); // get remote service proxydemoService.sayHello(&quot;world&quot;); dubbo 在客户端动态的生成了一个该 Interface 类型的代理类.在这个代理类中封装了远程服务调用的组件. DemoService 创建12&lt;dubbo:reference id=&quot;demoService&quot; group=&quot;g1&quot; check=&quot;true&quot; interface=&quot;com.alibaba.dubbo.demo.DemoService&quot;                     client=&quot;netty4&quot; timeout=&quot;10000&quot; callbacks=&quot;1000&quot;...</div></div></div></a><a class="pagination-related" href="/articles/dubbo/dubbo03-export.html" title="Dubbo 服务暴露"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-11-29</div><div class="info-item-2">Dubbo 服务暴露</div></div><div class="info-2"><div class="info-item-1">Dubbo 与 Spring 的结合代码在 dubbo-config 下的 dubbo-config-spring 模块中  META-INF&#x2F;dubbo.xsddubbo.xsd 定义了 dubbo 自定义标签 META-INF&#x2F;spring.schemasspring.schemas 指定了 dubbo.xsd 文件的位置. 1http\://code.alibabatech.com/schema/dubbo/dubbo.xsd=META-INF/dubbo.xsd  META-INF&#x2F;spring.handlers关联 DubboNamespaceHandler 命名空间处理器和 dubbo.xsd 中的 targetNamespace,即...</div></div></div></a><a class="pagination-related" href="/articles/dubbo/dubbo05-cluster.html" title="Dubbo Cluster"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-12-04</div><div class="info-item-2">Dubbo Cluster</div></div><div class="info-2"><div class="info-item-1">clusterCluster 将 Directory 中的多个 Invoker 伪装成一个 Invoker,对上层透明,伪装过程包含了容错逻辑,调用失败后,重试另一个. 集群模块处于服务提供者和消费者之间,对于服务消费者来说,集群可向其屏蔽服务提供者集群的情况,使其能够专心进行远程调用. cluster 继承结构 12345678910Cluster(com.alibaba.dubbo.rpc.cluster)    MergeableCluster(com.alibaba.dubbo.rpc.cluster.support)    FailfastCluster(com.alibaba.dubbo.rpc.cluster.support)    MockClusterWrapper(com.alibaba.dubbo.rpc.cluster.support.wrapper)    FailsafeCluster(com.alibaba.dubbo.rpc.cluster.support)   ...</div></div></div></a><a class="pagination-related" href="/articles/dubbo/dubbo06-provider.html" title="Dubbo Provider处理请求"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-12-05</div><div class="info-item-2">Dubbo Provider处理请求</div></div><div class="info-2"><div class="info-item-1">服务端接收并响应请求流程provider处理请求流程  123456789101112- NettyServerWorker线程接收请求    - ByteToMessageDecoder.channelRead()        - ByteToMessageDecoder.callDecode()            - NettyCodecAdapter.InternalDecoder.decode()                - DubboCountCodec.decode()解码        - fireChannelRead(ctx, out, size)            - NettyServerHandler.channelRead()                - AbstractPeer.received()                    - MultiMessageHandler.received()                        - HeartbeatHandler.received()            ...</div></div></div></a><a class="pagination-related" href="/articles/dubbo/dubbo07-heartbeat.html" title="Dubbo心跳机制"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-12-15</div><div class="info-item-2">Dubbo心跳机制</div></div><div class="info-2"><div class="info-item-1">Dubbo心跳机制Dubbo 默认客户端和服务端都会发送心跳报文,用来保持 TCP 长连接状态. 在客户端和服务端,Dubbo 都会开启一个线程 循环扫描 并 检测连接是否超时. 在服务端发现超时则会主动关闭客户端连接. 在客户端发现超时则会主动重新创建连接. 默认心跳检测时间是 60 秒. 原理provider 心跳默认是在 heartbeat(一分钟)内如果没有读消息或写消息,就会发送心跳请求消息,如果连着3次(180s)没有读消息,provider会关闭channel. consumer 端的心跳默认是在 一分钟 内如果没有读消息或写消息,就会发送心跳请求消息,如果连着3次(三分钟)没有读消息,consumer会进行重连. 开启定时任务provider 在启动 netty时,在 HeaderExchangeServer 的构造方法中,会通过 startHeatbeatTimer() 启动心跳定时任务.consumer 在 HeaderExchangeClient 的构造方法里,同样通过 startHeatbeatTimer()...</div></div></div></a></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="avatar-img"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info-name">flyingzc</div><div class="author-info-description">不积跬步无以至千里<br/>不积小流无以成江海</div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/FlyingZC"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/FlyingZC" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">FlyingZC's Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#SPI-%E6%9C%BA%E5%88%B6"><span class="toc-number">1.</span> <span class="toc-text">SPI 机制</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#SPI-%E4%BD%9C%E7%94%A8"><span class="toc-number">1.1.</span> <span class="toc-text">SPI 作用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Dubbo-%E5%AE%9E%E7%8E%B0%E7%9A%84-SPI-%E4%B8%8E-JDK-%E8%87%AA%E5%B8%A6%E7%9A%84-SPI-%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-number">1.2.</span> <span class="toc-text">Dubbo 实现的 SPI 与 JDK 自带的 SPI 的区别</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#SPI-%E9%85%8D%E7%BD%AE%E5%92%8C%E4%BD%BF%E7%94%A8"><span class="toc-number">1.3.</span> <span class="toc-text">SPI 配置和使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Dubbo-%E6%8B%93%E5%B1%95%E7%82%B9%E5%8A%A0%E8%BD%BD%E6%9C%BA%E5%88%B6%E7%9B%B8%E5%85%B3%E6%B3%A8%E8%A7%A3%E5%92%8C%E7%BB%84%E4%BB%B6"><span class="toc-number">1.4.</span> <span class="toc-text">Dubbo 拓展点加载机制相关注解和组件</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#SPI-%E6%B3%A8%E8%A7%A3"><span class="toc-number">1.4.1.</span> <span class="toc-text">@SPI 注解</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Adaptive-%E6%B3%A8%E8%A7%A3"><span class="toc-number">1.4.2.</span> <span class="toc-text">@Adaptive 注解</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Activate-%E6%B3%A8%E8%A7%A3"><span class="toc-number">1.4.3.</span> <span class="toc-text">@Activate 注解</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Wrapper"><span class="toc-number">1.4.4.</span> <span class="toc-text">Wrapper</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ExtensionLoader"><span class="toc-number">1.4.5.</span> <span class="toc-text">ExtensionLoader</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96-ExtensionLoader-%E6%B5%81%E7%A8%8B"><span class="toc-number">2.</span> <span class="toc-text">获取 ExtensionLoader 流程</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96-AdaptiveExtension-%E6%B5%81%E7%A8%8B"><span class="toc-number">3.</span> <span class="toc-text">获取 AdaptiveExtension 流程</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%A0%B9%E6%8D%AE-name-%E8%8E%B7%E5%8F%96%E6%8B%93%E5%B1%95%E7%82%B9%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%B5%81%E7%A8%8B"><span class="toc-number">4.</span> <span class="toc-text">根据 name 获取拓展点对象的流程</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#objectFactory-%E5%88%9B%E5%BB%BA%E7%9A%84%E9%80%BB%E8%BE%91"><span class="toc-number">5.</span> <span class="toc-text">objectFactory 创建的逻辑</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#SPI-IOC-%E6%B5%81%E7%A8%8B"><span class="toc-number">6.</span> <span class="toc-text">SPI IOC 流程</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#SPI-AOP-%E6%B5%81%E7%A8%8B"><span class="toc-number">7.</span> <span class="toc-text">SPI AOP 流程</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#SPI-Activate-%E6%B5%81%E7%A8%8B"><span class="toc-number">8.</span> <span class="toc-text">SPI @Activate 流程</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite03-transaction-begin.html" title="Apache Ignite 开启事务执行流程">Apache Ignite 开启事务执行流程</a><time datetime="2025-10-10T16:00:00.000Z" title="发表于 2025-10-11 00:00:00">2025-10-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite02-transaction.html" title="Apache Ignite 分布式事务原理">Apache Ignite 分布式事务原理</a><time datetime="2025-09-17T16:00:00.000Z" title="发表于 2025-09-18 00:00:00">2025-09-18</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite01-build.html" title="Apache Ignite IDEA 环境搭建">Apache Ignite IDEA 环境搭建</a><time datetime="2025-09-10T16:00:00.000Z" title="发表于 2025-09-11 00:00:00">2025-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/druid/druid01-resultset-leak.html" title="ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析">ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/jmeter/jmeter01-shardingsphere.html" title="Jmeter 压测 ShardingSphere">Jmeter 压测 ShardingSphere</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2025 By flyingzc</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>